﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using SGT_OClient.Views;
using System.Linq;
using System.Collections.ObjectModel;
using SGT_OClient.Model;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Data.Objects;

namespace SGT_OClient.ViewModel
{
    /// <summary>
    /// This class contains properties that the main View can data bind to.
    /// <para>
    /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
    /// </para>
    /// <para>
    /// You can also use Blend to data bind with the tool's support.
    /// </para>
    /// <para>
    /// See http://www.galasoft.ch/mvvm/getstarted
    /// </para>
    /// </summary>
    public class MainViewModel : ViewModelBase
    {
        private Remito _nuevoRemito;
        private Remito _remitoSeleccionado;
        private bool _esNuevo = false;
        private ObservableCollection<Remito> _remitos;
        public RelayCommand IrANuevoRemitoEntrada { get; private set; }
        public RelayCommand GuardarRemito { get; private set; }
        public RelayCommand EditarRemito { get; private set; }
        public RelayCommand ImprimirRemito { get; private set; }
        public RelayCommand EliminarRemito { get; private set; }
        private SGT_LocalBD contexto;


        public Remito RemitoSeleccionado
        {
            get { return _remitoSeleccionado; }
            set
            {

                _remitoSeleccionado = value;
                RaisePropertyChanged("RemitoSeleccionado");
            }
        }

        public Remito NuevoRemito
        {
            get { return _nuevoRemito; }
            set
            {

                _nuevoRemito = value;
                RaisePropertyChanged("NuevoRemito");
            }
        }

        public ObservableCollection<Remito> Remitos
        {
            get { return _remitos; }
            set
            {
                _remitos = value;
                RaisePropertyChanged("Remitos");

            }
        }

        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            if (IsInDesignMode)
            {
                // Code runs in Blend --> create design time data.
            }
            else
            {
                IrANuevoRemitoEntrada = new RelayCommand(abrirVentanaRemito);
                GuardarRemito = new RelayCommand(guardarRemito);
                EditarRemito = new RelayCommand(abrirVentanaRemitoActualizar);
                ImprimirRemito = new RelayCommand(Imprimir);
                EliminarRemito = new RelayCommand(Eliminar);
                contexto = new SGT_LocalBD();
                //Remitos = new ObservableCollection<Remito>();
                cargarRemitos();
               
            }
        }

        private void Eliminar()
        {
            if (RemitoSeleccionado != null)
            {
                MessageBoxResult res = MessageBox.Show("Se va eliminar el remito " + RemitoSeleccionado.Numero_Remito + ". ¿Está seguro?", "Confirmación",MessageBoxButton.YesNo);
                if (res == MessageBoxResult.Yes)
                {
                    contexto.Remito.DeleteObject(RemitoSeleccionado);
                    contexto.SaveChanges();
                    cargarRemitos();
                }
            }
        }


        private void Imprimir()
        {
            Plantilla3Vias p = new Plantilla3Vias();
            ScaleTransform scaleTransform = new ScaleTransform();
            scaleTransform.ScaleX = 0.9;
            scaleTransform.ScaleY = 0.9;
            p.RenderTransform = scaleTransform;
            Canvas c = new Canvas();
            c.Width = 797.8;
            c.Height = 1123.2;
            c.Children.Add(p);
            c.Measure(new Size(797.8,  1123.2));
            c.Arrange(new Rect(new Size(797.8,  1123.2)));
            c.UpdateLayout();
            PrintDialog dialog = new PrintDialog();
            if (dialog.ShowDialog() == true)
            {
                
                
                dialog.PrintVisual(c, "Remito " + NuevoRemito.Numero_Remito_Carga); 
            }
        }



        private void abrirVentanaRemito()
        {
            _esNuevo = true;
            NuevoRemito = new Remito();
            //NuevoRemito.IdRemito = Remitos.Count();
            NuevoRemito.IdRemito = obtenerMaxID() + 1;
            NuevoRemito.Numero_Remito_Carga = Int32.Parse(obtenerUltimoNroRemito()) + 1;
            NuevoRemito.Fecha = DateTime.Now;
            NuevoRemito.Hora_Llegada = DateTime.Now;
            NuevoRemito.Hora_Salida = DateTime.Now.AddDays(-2);

            IngresoRemitoView ventana = new IngresoRemitoView();
            ventana.ShowDialog();
        }

        private void abrirVentanaRemitoActualizar()
        {
            _esNuevo = false;
            NuevoRemito = RemitoSeleccionado;
            NuevoRemito.Fecha = DateTime.Now;
            
            IngresoRemitoView ventana = new IngresoRemitoView();
            ventana.ShowDialog();

        }

        private void guardarRemito()
        {

            
            

            if (_esNuevo)
                contexto.Remito.AddObject(NuevoRemito);
            
                
                
            
            try
            {
                contexto.SaveChanges();

                if (_esNuevo)
                {
                    //Remitos.Add(NuevoRemito);
                    cargarRemitos();
                    
                }
                MessageBox.Show("Guardado OK");

            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR: " + ex.Message);
            }

            
        }

        private void cargarRemitos()
        {

            if (Remitos != null)
                Remitos.Clear();
            else
                Remitos = new ObservableCollection<Remito>();
            var lista = from l in contexto.Remito
                        orderby l.Numero_Remito_Carga descending
                        select l;
            foreach (Remito r in lista)
            {
                if (r.IdRemito != 0)
                    Remitos.Add(r);
            }
            

        }

        private int  obtenerMaxID()
        {
            var mID = (from r in contexto.Remito
                       select r.IdRemito).Max();
            return mID;
        }

        private string obtenerUltimoNroRemito()
        {
            int max = obtenerMaxID();
            var mID = (from r in contexto.Remito
                      where r.IdRemito == max
                      select r.Numero_Remito).Single();
            if (mID == null)
                mID = "0";
            return mID;
        }


        ////public override void Cleanup()
        ////{
        ////    // Clean up if needed

        ////    base.Cleanup();
        ////}
    }
}